package edu.hd4ic.gui.controlls;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;

/**
 * @author morfant
 */
public class IconWithDescriptionListCellRenderer extends JPanel implements ListCellRenderer {

    private DefaultListCellRenderer defaultListCellRenderer = new DefaultListCellRenderer();
    private JLabel imageLabel = new JLabel();
    private JLabel descriptionLabel = new JLabel();
    private int numberOfSymbolInDisplayedPartOfDescription;

    public IconWithDescriptionListCellRenderer(int numberOfSymbolInDisplayedPartOfDescription) {
        setLayout(new BorderLayout());
        Border emptyBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
        imageLabel.setBorder(emptyBorder);
        descriptionLabel.setBorder(emptyBorder);
        add(imageLabel, BorderLayout.CENTER);
        add(descriptionLabel, BorderLayout.SOUTH);
        this.numberOfSymbolInDisplayedPartOfDescription=numberOfSymbolInDisplayedPartOfDescription;
    }

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        defaultListCellRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        setBorder(defaultListCellRenderer.getBorder());
        setBackground(defaultListCellRenderer.getBackground());
        IconWithDescription scaledImageIcon = (IconWithDescription) value;
        imageLabel.setIcon(scaledImageIcon);
        String description = scaledImageIcon.getDescription();
        if (description.length() < numberOfSymbolInDisplayedPartOfDescription) {
            descriptionLabel.setText(description.substring(description.length() - numberOfSymbolInDisplayedPartOfDescription));
        } else {
            descriptionLabel.setText(description);
        }
        return this;
    }
}
